/* 初始化分离文件和文件夹 */
const readerDataTransfer = async (dtf, callBack) => {
  log('开始读取****************')
  let isFiles = []
  let isEntry = []
  let tempFiles = {
    notEntryFiles: null,
    EntryFiles: []
  }
  /*  因为我这是electron打包，所以只针对Chrome处理, 其他浏览器请针对api做相应的处理 */
  if (dtf.items !== undefined) {
    dtf.items.forEach(entry => { // 用for循环会丢失datatransferitem
      const dtfInfo = entry.webkitGetAsEntry() // 这步避免文件夹目录，快捷方式
      if (entry.kind === 'file' && dtfInfo.isFile) { // 文件
        isFiles.push(entry.getAsFile())
        return
      }
      if (entry.kind === 'file' && dtfInfo.isDirectory) { // 文件夹
        isEntry.push({name: dtfInfo.name, dtfInfo: dtfInfo})
      }
    })
  }
  if (isFiles.length) {
    tempFiles.notEntryFiles = await readFiles(isFiles)
  }
  if (isEntry.length) {
    for(let i = 0; i < isEntry.length; i++) { // 这里没做同步，读完一个文件夹展示一个
      let entry = isEntry[i]
      let fileContent = await readDir(entry.dtfInfo) // 开始读取文件夹，直到读完返回文件信息加链接
      tempFiles.EntryFiles.push(fileContent)
    }
  }
  log('读取结束****************')
  callBack(tempFiles)
}
/* 
  将文件转为引用链接和文字内容
  1. 转换完渲染，做异步处理
  2. 边转换边渲染，直接在readxxx中赋值给observe的对象，文件夹内数组对象监听不成功用set赋值
*/
const readFiles = async (fileList) => {
  log('开始转换成url和文本数据')
  let fileInfo = {
    text: [],
    img: [],
    video: [],
    other: []
  }
  for (let i = 0; i < fileList.length; i++) {
    const file = fileList[i]
    log(`转换${file.name}文件`)
    if (file.type.indexOf('text') > -1) {
      let text =  await readText(file, 'utf8')
      fileInfo.text.push(text)
      continue
    }
    if (file.type.indexOf('image') > -1) {
      let img = await readImg(file)
      fileInfo.img.push(img)
      continue
    }
    if (file.type.indexOf('video') > -1) {
      let video =  await readVideo(file)
      fileInfo.video.push(video)
      continue
    }
    fileInfo.other.push({name: file.name})
  }
  log('转换结束')
  return new Promise(resolve => {
    resolve(fileInfo)
  })
}
/* 读取文件夹 */
const readDir = async (entry) => {
  log(`开始读取-${entry.name}-文件夹`)
  let temp = await readFileEntry(entry)
  let files = await readDirFiles(temp)
  let filesCotent = await readFiles(files.files)
  filesCotent.name = entry.name
  filesCotent.children = files.children
  log(`读取-${entry.name}-文件夹结束`)
  return new Promise(resolve => {
    resolve(filesCotent)
  })
}
/* 读取文件夹中的fileEntry */
const readFileEntry = async (dtfInfo) => {
  log(`开始读取-${dtfInfo.name}-里的fileEntry`)
  return new Promise(resolve => {
    let isFileEntry = []
    const dirReader = dtfInfo.createReader()
    dirReader.readEntries(fileEntries => { // 异步函数，拿到所有fileEntry再进行下一步
      for (let i = 0; i < fileEntries.length; i++) {
        isFileEntry.push(fileEntries[i])
      }
      log(`读取-${dtfInfo.name}-里的fileEntry结束`)
      resolve(isFileEntry)
    })
  })
}
/* 读取fileEntry包裹的文件 */
const readDirFiles = async (fileEntryList) => {
  log(`开始获取fileEntry里的文件`)
  let isFiles = {files: [], children: []}
  for (let i = 0 ; i < fileEntryList.length; i++) {
    let item = fileEntryList[i]
    if (item.isFile) {
      let file = await syncFileReader(item)
      log(`获取${file.name}成功`)
      isFiles.files.push(file)
      continue
    }
    if (item.isDirectory) {
      let childrenFile = await readDir(item)
      log(`获取完子类${item.name}文件夹下所有文件成功`)
      isFiles.children.push(childrenFile)
    }
  }
  log(`获取fileEntry里的文件结束`)
  return new Promise(resolve => {
    resolve(isFiles)
  })
}
/* 处理异步读取 */
const syncFileReader = (item) => {
  return new Promise(resolve => {
    item.file(file => {
      resolve(file)
    })
  })
}

const readText = (textFile, encodeType) => {
  return new Promise((resolve) => {
    const fileReader = new FileReader()
    fileReader.readAsText(textFile, encodeType)
    fileReader.onload = (e) => {
      resolve({
        name: textFile.name,
        content: e.target.result
      })
    }
  })
}

const readImg = (imgFile) => {
  return new Promise((resolve) => {
    resolve({
      name: imgFile.name,
      content: URL.createObjectURL(imgFile)
    })
  })
}

const readVideo = (videoFile) => {
  return new Promise((resolve) => {
    resolve({
      name: videoFile.name,
      content: URL.createObjectURL(videoFile)
    })
  })
}

const log = (text) => {
  console.log(new Date().toISOString(), text)
}

export default readerDataTransfer